const app = getApp()

const request = (url, options) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.host}${url}`,
      method: options.method,
      data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
      header: {
        'Content-Type': 'application/json; charset=UTF-8',
        'Authorization': wx.getStorageSync('token')  // 看自己是否需要
      },
      success(request) {
        if (request.data.code === 200) {
          resolve(request.data)
        } else {
          reject(request.data)
        }
      },
      fail(error) {
        reject(error.data)
      }
    })
  })
}
const request1 = (url, options) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.host}${url}`,
      method: options.method,
      data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
      header: {
        'Content-Type': 'application/json; charset=UTF-8',
      },
      success(request) {
        if (request.data.code === 200) {
          resolve(request.data)
        } else {
          reject(request.data)
        }
      },
      fail(error) {
        reject(error.data)
      }
    })
  })
}

const uploadFileRequest = (url,data)=>{
  return new Promise((resolve, reject) => {
  wx.uploadFile({
    filePath: data,
    name: 'file',
    url: `${app.globalData.host}`+ url,
    header: {
      'Content-Type': 'application/json; charset=UTF-8',
      'Authorization': wx.getStorageSync('token')  // 看自己是否需要
    },
    success:function(request){
      let data = JSON.parse(request.data)
      if (data.code === 200) {
        resolve(data)
      } else {
        reject(data)
      }
    },
    fail : function(err){
        reject(request.data)
       }
     })
    })
  }


const get = (url, options = {}) => {
  return request(url, { method: 'GET', data: options })
}

const uploadFile = (url, options = {}) => {
  return uploadFileRequest(url, options)
}
const notGet = (url, options = {}) => {
  return request1(url, { method: 'GET', data: options })
}

const post = (url, options) => {
  return request(url, { method: 'POST', data: options })
}

const put = (url, options) => {
  return request(url, { method: 'PUT', data: options })
}

// 不能声明DELETE（关键字）
const remove = (url, options) => {
  return request(url, { method: 'DELETE', data: options })
}

module.exports = {
  get,
  post,
  put,
  remove,
  notGet,
  uploadFile
}